import { prisma } from "../prisma/client";
import bcrypt from "bcryptjs"; // 用于密码加密
import { PaginationUtil } from "../utils/pagination.util";
// 获取所有用户(角色 & 部门)
export const getAllUsers = async (
  page: number = 1,
  pageSize: number = 10,
  options: object = {}
) => {
  return PaginationUtil.paginate(
    prisma.user,
    {
      include: {
        role: true,
        department: true,
      },
      ...options,
    },
    page,
    pageSize
  );
};

// 根据ID获取用户
export const getUserById = async (id: number) => {
  return await prisma.user.findUnique({
    where: { id },
    include: {
      role: true,
      department: true,
    },
  });
};

// 创建用户
export const createUser = async (data: {
  username: string;
  password: string;
  email?: string;
  phone?: string;
  roleId: number;
  departmentId: number;
}) => {
  // 加密密码
  const hashedPassword = await bcrypt.hash(data.password, 10);
  return await prisma.user.create({
    data: {
      ...data,
      password: hashedPassword,
    },
  });
};

// 更新用户信息
export const updateUser = async (
  id: number,
  data: {
    username?: string;
    password?: string;
    email?: string;
    phone?: string;
    roleId?: number;
    departmentId?: number;
  }
) => {
  const updateDate = { ...data };
  if (data.password) {
    updateDate.password = await bcrypt.hash(data.password, 10);
  }
  return await prisma.user.update({
    where: { id },
    data: updateDate,
  });
};

// 删除用户
export const deleteUser = async (id: number) => {
  return await prisma.user.delete({
    where: { id },
  });
};

// 登录验证
export const verifyLogin = async (username: string, password: string) => {
  const user = await prisma.user.findFirst({
    where: { username },
    include: {
      role: true,
      department: true,
    },
  });
  if (!user) return null;
  const isMatch = await bcrypt.compare(password, user.password);
  if (!isMatch) return null;
  delete (user as any).password;
  return user;
};
